home *** CD-ROM | disk | FTP | other *** search
/ Collection of Tools & Utilities / Collection of Tools and Utilities.iso / c / cug173.zip / LEX.MEM < prev    next >
Text File  |  1984-01-17  |  74KB  |  2,347 lines

  1. /*
  2.   HEADER: CUG    nnn.nn;
  3.   TITLE:         LEX - A Lexical Analyser Generator
  4.   VERSION:       1.0 for IBM-PC
  5.   DATE:          Sep 29, 195
  6.   DESCRIPTION:   A Lexical Analyser Generator. From UNIX
  7.   KEYWORDS:      Lexical Analyser Generator YACC C PREP
  8.   SYSTEM:        IBM-PC and Compatiables
  9.   FILENAME:      LEX.MEM
  10.   WARNINGS:      This program is not for the casual user. It will
  11.                  be useful primarily to expert developers.
  12.   CRC:           N/A
  13.   SEE-ALSO:      YACC and PREP
  14.   AUTHORS:       Scott Guthery 11100 leadfwood lane Austin, TX 78750
  15.   COMPILERS:     DESMET-C
  16.   REFERENCES:    UNIX Systems Manuals
  17. */
  18.  
  19.  
  20.  
  21.  
  22.  
  23.  
  24.  
  25.  
  26.  
  27.  
  28.  
  29.  
  30.  
  31.  
  32.  
  33.  
  34.  
  35.  
  36.  
  37.  
  38.  
  39.  
  40.  
  41.  
  42.  
  43.  
  44.  
  45.  
  46.  
  47.  
  48.  
  49.  
  50.  
  51.  
  52.  
  53.  
  54.  
  55.  
  56.  
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63.  
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.  
  71.  
  72.  
  73.  
  74.  
  75.  
  76.  
  77.  
  78.  
  79.  
  80.  
  81.  
  82.  
  83.  
  84.          
  85.  
  86.  
  87.  
  88.  
  89.  
  90.  
  91.  
  92.  
  93.  
  94.  
  95.  
  96.  
  97.  
  98.  
  99.  
  100.  
  101.  
  102.  
  103.  
  104.  
  105.  
  106.  
  107.  
  108.  
  109.  
  110.  
  111.                             DECUS C LANGUAGE SYSTEM
  112.  
  113.  
  114.                                       LEX
  115.                           A lexical Analyser Generator
  116.  
  117.  
  118.                                        by
  119.  
  120.                                Charles H. Forsyth
  121.  
  122.                             University of Waterloo
  123.                             Waterloo, Ontario, N2L 3G1
  124.                             Canada
  125.  
  126.  
  127.                                    Revised by
  128.  
  129.                          Robert B. Denny & Martin Minow
  130.  
  131.  
  132.         LEX  transforms  a  regular-expression  grammar  and  associated
  133.         action  routines into a C function and set of tables, yielding a
  134.         table-driven lexical analyser which manages to  be  compact  and
  135.         rapid.
  136.  
  137.  
  138.                          DECUS Structured Languages SIG
  139.  
  140.                               Version of 30-Oct-82
  141.  
  142.  
  143.  
  144.  
  145.  
  146.  
  147.  
  148.  
  149.  
  150.            
  151.  
  152.  
  153.  
  154.  
  155.  
  156.  
  157.  
  158.  
  159.                      Copyright (C) 1978, Charles H. Forsyth
  160.  
  161.  
  162.  
  163.  
  164.  
  165.                  Modifications Copyright (C) 1980, 1982, DECUS
  166.  
  167.             General permission  to  copy  or  modify,  but  not  for
  168.             profit,  is  hereby  granted,  provided  that  the above
  169.             copyright notice is included and reference made  to  the
  170.             fact that reproduction privileges were granted by DECUS.
  171.  
  172.             The information in this document is  subject  to  change
  173.             without   notice  and  should  not  be  construed  as  a
  174.             commitment by Digital Equipment Corporation or by DECUS.
  175.  
  176.             Neither Digital Equipment Corporation,  DECUS,  nor  the
  177.             authors   assume  any  responsibility  for  the  use  or
  178.             reliability of this document or the described software.
  179.  
  180.             This software is  made  available  without  any  support
  181.             whatsoever.     The    person    responsible    for   an
  182.             implementation of this system should expect to  have  to
  183.             understand  and  modify  the source code if any problems
  184.             are  encountered  in  implementing  or  maintaining  the
  185.             compiler or its run-time library.  The DECUS 'Structured
  186.             Languages Special Interest Group' is the  primary  focus
  187.             for communication among users of this software.
  188.  
  189.  
  190.  
  191.  
  192.  
  193.  
  194.  
  195.  
  196.  
  197.         UNIX is  a  trademark  of  Bell  Telephone  Laboratories.   RSX,
  198.         RSTS/E,  RT-11  and  VMS  are  trademarks  of  Digital Equipment
  199.         Corporation.
  200.  
  201.  
  202.  
  203.  
  204.  
  205.  
  206.  
  207.  
  208.  
  209.  
  210.  
  211.  
  212.  
  213.  
  214.  
  215.  
  216.         A Lexical Analyser Generator                              
  217.  
  218.  
  219.         1.0  Introduction
  220.  
  221.              ____________
  222.  
  223.  
  224.         A computer program often has an input stream which  is  composed
  225.         of  small elements, such as a stream of characters, and which it
  226.         would like to convert to larger elements in order to process the
  227.         data  conveniently.   A  compiler  is a common example of such a
  228.         program:  it reads a stream of characters forming a program, and
  229.         would  like  to turn this sequence of characters into a sequence
  230.         of larger items, namely identifiers, numbers, and operators, for
  231.         parsing.   In  a  compiler,  the  procedures  which  do this are
  232.         collectively called the  lexical  analyser,  or  scanner;   this
  233.  
  234.                                  _______  ________       _______
  235.         terminology will be used more generally here.
  236.  
  237.         It may happen that the speed with which this  transformation  is
  238.         done  will  noticeably affect the speed at which the rest of the
  239.         program operates.  It is certainly true that although such  code
  240.         is  rarely  difficult to write, writing and debugging it is both
  241.         tedious, and time-consuming,  and  one  typically  would  rather
  242.         spend  the  time  on  the hard parts of the program.  It is also
  243.         true that while certain transformations are easily  thought  of,
  244.         they   are  often  hard  to  express  succinctly  in  the  usual
  245.         general-purpose programming languages (eg, the description of  a
  246.         floating-point number).
  247.  
  248.         LEX is a program which tries to give a programmer a good deal of
  249.         help  in  this,  by  writing large parts of the lexical analyser
  250.         automatically, based on a description supplied by the programmer
  251.         of  the  items  to be recognised (which are known as tokens), as
  252.  
  253.                                                              ______
  254.         patterns of the more basic elements of the  input  stream.   The
  255.         LEX  description  is  very  much  a special-purpose language for
  256.         writing lexical analysers, and LEX is then simply  a  translator
  257.         for  this  language.  The LEX language is easy to write, and the
  258.         resulting processor is compact and fast running.
  259.  
  260.         The purpose of a LEX program is to read  an  input  stream,  and
  261.         recognise tokens.  As the lexical analyser will usually exist as
  262.  
  263.                   ______
  264.         a subroutine in a larger set  of  programs,  it  will  return  a
  265.         "token  number",  which  indicates  which  token  was found, and
  266.         possibly  a  "token  value",  which   provides   more   detailed
  267.         information  about the token (eg, a copy of the token itself, or
  268.         an index into a symbol  table).   This  need  not  be  the  only
  269.         possibility;   a  LEX program is often a good description of the
  270.         structure of the whole computation, and  in  such  a  case,  the
  271.         lexical  analyser might choose to call other routines to perform
  272.         the necessary actions whenever a particular token is recognised,
  273.         without reference to its own caller.
  274.  
  275.  
  276.  
  277.  
  278.  
  279.  
  280.  
  281.  
  282.  
  283.  
  284.  
  285.  
  286.         A Lexical Analyser Generator                                 
  287.  
  288.  
  289.         2.0  The Lex Language
  290.  
  291.              ___ ___ ________
  292.  
  293.         LEX transforms a regular-expression grammar into a deterministic
  294.         finite-state  automaton that recognizes that grammar.  Each rule
  295.         of the grammar is associated with  an  action  which  is  to  be
  296.         performed  when  that rule successfully matches some part of the
  297.         input data.
  298.  
  299.         Because of the nature of regular  expression  grammars,  certain
  300.         language  constructions  cannot  be  recognized by LEX programs.
  301.         Specifically, expressions with balanced  parentheses  cannot  be
  302.         recognized.  This means that LEX cannot be used to recognize all
  303.         Fortran keywords as some  (DO,  IF,  and  FORMAT,  for  example)
  304.         require  elaborate  recognition to distinguish between ambiguous
  305.         constructions.
  306.  
  307.  
  308.  
  309.         2.1  Elementary Things
  310.  
  311.              __________ ______
  312.  
  313.  
  314.         Strings,  characters,  sets  of  characters   called   character
  315.         classes,  and  operators  to  form  these into patterns, are the
  316.         fundamental elements of the LEX language.
  317.  
  318.         A string is a sequence of  characters,  not  including  newline,
  319.  
  320.           ______
  321.         enclosed  in  quotes,  or  apostrophes.   Within  a  string, the
  322.         following escape sequences
  323.         (which are those of the C language) allow any 8-bit character to
  324.         be  represented,  including  the  escape  character, quotes, and
  325.         newlines:
  326.  
  327.                 \n      NL      (012)
  328.                 \r      CR      (015)
  329.                 \b      BS      (010)
  330.                 \t      TAB     (011)
  331.                 \"      "
  332.                 \'      '
  333.                 \c      c
  334.                 \\      \
  335.                 \NNN    (NNN)
  336.  
  337.         where NNN  is  a  number  in  octal,  and  c  is  any  printable
  338.  
  339.                                                    _
  340.         character.   A  string may be continued across a line by writing
  341.         the escape character before the newline.
  342.  
  343.         Outside a string, a sequence of upper-case letters stands for  a
  344.         sequence  of the equivalent lower-case letters, while a sequence
  345.  
  346.                                     __________
  347.         of lower-case letters is taken as the name of a LEX  expression,
  348.         and  handled  specially,  as described below.  These conventions
  349.         make the  use  of  named  expressions  and  the  description  of
  350.         lower-case  keywords (the usual case on Unix) fairly convenient.
  351.         Keywords in case-independent languages, such as Fortran, require
  352.         additional effort to match, as will be noted.
  353.  
  354.  
  355.  
  356.  
  357.  
  358.         A Lexical Analyser Generator                                      Pa
  359.  
  360.  
  361.         An Ascii character other than one of
  362.  
  363.                 () {} [ * | = ; % / \ ' " -
  364.  
  365.         may be used in LEX to stand for itself.
  366.  
  367.         A sequence of characters enclosed  by  brackets  ('['  and  ']')
  368.         forms  a  character class, which stands for all those characters
  369.         within the brackets.  If a circumflex ('^') follows the  opening
  370.         bracket,  then  the  class  will  instead  stand  for  all those
  371.         characters but those inside the brackets.  The escapes  used  in
  372.  
  373.                    ___
  374.         strings may be used in character classes as well.
  375.  
  376.         Within a character class, the construction "A-B" (where "A"  and
  377.         "B" are arbitrary characters) stands for the range of characters
  378.         between "A" and "B" inclusive.
  379.  
  380.         For example,
  381.  
  382.                 "ABC"           matches "abc"
  383.  
  384.                 "[ABC]"         matches "A" or "B" or "C"
  385.  
  386.                 "[A-Za-z0-9]"   matches all letters and digits
  387.  
  388.         Case-independent keyword recognition may be described  by  using
  389.         auxiliary  definitions  to  define expressions that match either
  390.         case.  For example,
  391.  
  392.                 a = [Aa];
  393.                 b = [Bb];
  394.                 ...
  395.                 z = [Zz];
  396.                 %%
  397.                 d o             Matches "DO", "do", "Do", or "dO"
  398.  
  399.  
  400.  
  401.  
  402.         2.2  Putting Things Together
  403.  
  404.              _______ ______ ________
  405.  
  406.  
  407.         Several operators are provided to allow construction of  a  type
  408.         of pattern called a regular expression.  Such expressions can be
  409.  
  410.                             _______ __________
  411.         implemented as finite-state automata (without memory or stacks).
  412.         A  reference  to  an  "occurrence"  of  a  regular expression is
  413.         generally taken to mean an occurrence of any string  matched  by
  414.         that  regular  expression.  The operators are presented in order
  415.         of decreasing priority.  In all cases, operators work on  either
  416.         strings or character classes, or on other regular expressions.
  417.  
  418.         Any string or character class forms a regular  expression  which
  419.         matches  whatever  the  string or character class stands for (as
  420.         described above).
  421.  
  422.  
  423.  
  424.  
  425.  
  426.  
  427.         A Lexical Analyser Generator                                      P
  428.  
  429.  
  430.         The operator '*' applied following a regular expression forms  a
  431.         new  regular  expression  which matches an arbitrary number (ie,
  432.         zero or more) of  adjacent  occurrences  of  the  first  regular
  433.         expression.   The  operation  is  often  referred to as (Kleene)
  434.         closure.
  435.  
  436.         The operation of concatenation of  two  regular  expressions  is
  437.  
  438.                          _____________
  439.         expressed  simply by writing the regular expressions adjacent to
  440.         each  other.   The  resulting  regular  expression  matches  any
  441.         occurrence  of the first regular expression followed directly by
  442.         an occurrence of the second regular expression.
  443.  
  444.         The operator  '|',  alternation,  written  between  two  regular
  445.  
  446.                             ___________
  447.         expressions   forms   a  regular  expression  which  matches  an
  448.         occurrence of the first regular expression or an  occurrence  of
  449.         the second regular expression.
  450.  
  451.         Any regular expression may be enclosed in parentheses  to  cause
  452.         the priority of operators to be overridden in the usual manner.
  453.  
  454.         A few examples should help to make all of this clear:
  455.  
  456.                 "[0-9]*"        matches a (possibly empty)  sequence  of
  457.                                 digits.
  458.  
  459.                 "[A-Za-z_$][A-Za-z0-9_$]*"
  460.                                 matches a C identifier.
  461.  
  462.                 "([A-Za-z_$]|[0-9])*"
  463.                                 matches a C identifier, or a sequence of
  464.                                 digits,  or  a  sequence  of letters and
  465.                                 digits intermixed, or nothing.
  466.  
  467.  
  468.  
  469.  
  470.         2.3  The General Form of Lex Programs
  471.  
  472.              ___ _______ ____ __ ___ ________
  473.  
  474.  
  475.         A LEX source input file consists of three sections:   a  section
  476.         containing   auxiliary   definitions,   a   section   containing
  477.  
  478.                      _________   ___________
  479.         translations, and a section containing programs.
  480.  
  481.         ____________                           ________
  482.  
  483.         Throughout a LEX program, spaces, tabs, and newlines may be used
  484.         freely, and PL/1-style comments:
  485.  
  486.                 /* ... anything but '*/' ... */
  487.  
  488.         may be used, and are treated as a space.
  489.  
  490.         The auxiliary definition section must be present, separated from
  491.  
  492.             _________ __________
  493.         following  sections  by the two-character sequence '%%', but may
  494.         be empty.  This  section  allows  definition  of  named  regular
  495.  
  496.  
  497.  
  498.  
  499.  
  500.         expressions,  which  provide  the useful ability to use names of
  501.         regular expressions in the  translation  section,  in  place  of
  502.  
  503.  
  504.  
  505.  
  506.  
  507.  
  508.  
  509.  
  510.  
  511.  
  512.  
  513.  
  514.  
  515.  
  516.  
  517.  
  518.  
  519.  
  520.  
  521.  
  522.  
  523.  
  524.  
  525.  
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532.  
  533.  
  534.  
  535.  
  536.  
  537.  
  538.  
  539.  
  540.  
  541.  
  542.  
  543.  
  544.  
  545.  
  546.  
  547.  
  548.  
  549.  
  550.  
  551.  
  552.  
  553.  
  554.  
  555.  
  556.  
  557.  
  558.  
  559.  
  560.  
  561.  
  562.  
  563.  
  564.  
  565.  
  566.         A Lexical
  567.  
  568.  
  569.         common sub-expressions, or to make that section more readable.
  570.  
  571.         The translation section follows the '%%' sequence, and  contains
  572.  
  573.             ___________
  574.         regular  expressions paired with actions which describe what the
  575.  
  576.                                          _______
  577.         lexical analyser should do when it discovers an occurrence of  a
  578.         given regular expression in its input stream.
  579.  
  580.         The program section may be omitted;  if it is present it must be
  581.  
  582.             _______
  583.         separated from the translation section by the '%%' sequence.  If
  584.         present, it may contain anything in general,  as  it  is  simply
  585.         tacked on to the end of the LEX output file.
  586.  
  587.         The style of this layout will be familiar to users of Yacc.   As
  588.         LEX  is  often used with that processor, it seemed reasonable to
  589.         keep to a similar format.
  590.  
  591.  
  592.  
  593.         2.4  Auxiliary Definitions
  594.  
  595.              _________ ___________
  596.  
  597.  
  598.         Given the set of regular expressions forming a complete  syntax,
  599.         there  are often common sub-expressions.  LEX allows these to be
  600.         named, defined  but  once,  and  referred  to  by  name  in  any
  601.         subsequent   regular  expression.   Note  that  definition  must
  602.         precede use.  A definition has the form:
  603.  
  604.                 expression_name = regular_expression ;
  605.  
  606.         where a name is composed of a lower-case letter  followed  by  a
  607.         sequence  string  of letters and digits, and where an underscore
  608.         is considered a letter.  For example,
  609.  
  610.                 digit   = [0-9];
  611.                 letter  = [a-zA-Z];
  612.                 name    = letter(letter|digit)*;
  613.  
  614.         The semicolon is needed to resolve some ambiguities in  the  LEX
  615.         syntax.
  616.  
  617.         Three  auxiliary  definitions  have  special  meaning  to   LEX:
  618.         "break",  "illegal",  and  "ignore."  They  are  all  defined as
  619.         character classes ("break = [,.?]", for example) and are used as
  620.         follows:
  621.  
  622.                 break   An input token will always terminate if a member
  623.                         of the "break" class is scanned.
  624.  
  625.                 illegal The "illegal"  class  allows  simplification  of
  626.                         error detection, as will be described in a later
  627.                         section.  If this  class  is  defined,  and  the
  628.                         lexical  analyser  stops  at  a  character  that
  629.                         "cannot"  occur  in  its  present  context,  the
  630.                         analyser  will  output  a suitable error message
  631.                         and ignore the offender.
  632.  
  633.  
  634.  
  635.  
  636.  
  637.         A Lexical Analyser Generator                                      Pa
  638.  
  639.  
  640.                 ignore  This class defines a set of characters that  are
  641.                         ignored by the analyser's input routine.
  642.  
  643.  
  644.  
  645.  
  646.         2.5  Translations
  647.  
  648.              ____________
  649.  
  650.  
  651.         One would like to provide a description  of  the  action  to  be
  652.         taken  when  a  particular sequence of input characters has been
  653.         matched by a given regular expression.  The kind of action taken
  654.         might  vary  considerably, depending upon the application.  In a
  655.         compiler, typical actions are:  enter an identifer into a symbol
  656.         table,  read and store a string, or return a particular token to
  657.         the parser.  In text processing, one  might  wish  to  reproduce
  658.         most  of  the input stream on an output stream unchanged, making
  659.         substitutions when a particular sequence of characters is found.
  660.         In  general,  it  is  hard to predict what form the action might
  661.         take, and so, in LEX the nature of the action  is  left  to  the
  662.         user,  by allowing specification, for each regular expression of
  663.         interest, C-language code to be executed when a string  matching
  664.         that  expression  is  discovered  by  the driving program of the
  665.         lexical  analyser.   An  action,  together  with   its   regular
  666.         expression, is called a translation, and has the format:
  667.  
  668.                                 ___________
  669.  
  670.                 regular_expression { action }
  671.  
  672.         All of this may be spread across several lines.  The action  may
  673.         be empty, but the braces must appear.
  674.  
  675.         Earlier, it was argued that most general-purpose  languages  are
  676.         inappropriate for writing lexical analysers, and it is important
  677.         to see that the subsequent use of such a language  to  form  the
  678.         actions  is not a contradiction.  Most languages are fairly good
  679.         at  expressing  the  actions  described  above   (symbol   table
  680.         manipulation,  writing  character  strings,  and such).  Leaving
  681.         this part of the lexical analyser to those  languages  therefore
  682.         not  only  makes  sense,  but also ensures that decisions by the
  683.         writer of the lexical analyser generator will not  unduly  cramp
  684.         the  user's style.  However, general-purpose languages do not as
  685.         a rule provide inexpensive pattern matching facilities, or input
  686.         description formats, appropriate for describing or structuring a
  687.         lexical analyser.
  688.  
  689.         Allowing a user to provide his own code is not really enough, as
  690.         he  will  need  some  help  from  LEX  to obtain a copy of, or a
  691.         pointer to, the current token, if nothing else.  LEX provides  a
  692.         library  of C functions which may be called to obtain controlled
  693.         access to some of  the  data  structures  used  by  the  driving
  694.         programs  of  the  lexical  analyser.   These are described in a
  695.         later section.
  696.  
  697.  
  698.  
  699.  
  700.  
  701.  
  702.  
  703.  
  704.  
  705.         A Lexical Analyser Generator                                    
  706.  
  707.  
  708.         2.5.1  Numbers and Values -
  709.  
  710.                _______ ___ ______
  711.  
  712.         Typically, a lexical analyser will return a value to its  caller
  713.         indicating  which  token has been found.  Within an action, this
  714.         is done by writing a  C  return  statement,  which  returns  the
  715.  
  716.                                  ______
  717.         appropriate value:
  718.  
  719.                 BEGIN   {
  720.                                 return(T_BEGIN);
  721.                         }
  722.                 name    {
  723.                                 lookup(token(NULL));
  724.                                 return(T_NAME);
  725.                         }
  726.                 "/"     {
  727.                                 return('/');
  728.                         }
  729.  
  730.         Note that function lookup() is provided by the user program.
  731.  
  732.         In many cases, other information must be supplied to its  caller
  733.         by  the scanner.  When an identifier is recognised, for example,
  734.         both a pointer to a symbol-table entry,  and  the  token  number
  735.         T_NAME  must  be returned, yet the C return statement can return
  736.  
  737.                                              ______
  738.         but a single value.  Yacc has a  similar  problem,  and  so  its
  739.         lexical  analyser  sets  an  external word 'yylval' to the token
  740.         value, while the token number is returned by the  scanner.   LEX
  741.         uses  the external 'yylval' (to be compatible), but, to make LEX
  742.         programs more readable when used alone, the name 'lexval' is set
  743.         by a #define statement to 'yylval'.  For example,
  744.  
  745.                 name    {
  746.                                 lexval = lookup(token(NULL));
  747.                                 return(T_NAME);
  748.                         }
  749.  
  750.  
  751.         Certain  token  numbers  are  treated  specially;    these   are
  752.         automatically defined as manifests (see section 3.2) by LEX, and
  753.         all begin with the sequence 'LEX...' so as not to clash with the
  754.         user's own names.  There are two such tokens defined at present:
  755.  
  756.                 LEXSKIP When  returned  by  a  user's  action   routine,
  757.                         LEXSKIP  causes  the  lexical analyser to ignore
  758.                         the current token (ie, it does  not  inform  the
  759.                         parser of its presence), and to look instead for
  760.                         a new token.  This may be used  when  a  comment
  761.                         sequence has been discovered, and discarded.  It
  762.                         is also useful when the action routine completes
  763.                         processing  of the token.  See the discussion of
  764.                         the comment() library function for an example of
  765.                         its usage.
  766.  
  767.                 LEXERR  This  is  returned  by  the   lexical   analyser
  768.                         (function  yylex()) when an unrecognizable input
  769.  
  770.  
  771.  
  772.  
  773.  
  774.         A Lexical Analyser Generator                                     Pag
  775.  
  776.  
  777.                         sequence has been detected.  By default,  LEXERR
  778.                         is 256.  This the same as the yacc error value.
  779.  
  780.  
  781.         To summarise, the token number is  set  by  the  action  with  a
  782.         return   statement,   and   the   token   value  (ie,  auxiliary
  783.  
  784.         ______
  785.         information) is set by assigning  this  value  to  the  external
  786.         integer 'lexval'.
  787.  
  788.  
  789.  
  790.         2.6  Declaration Sections
  791.  
  792.              ___________ ________
  793.  
  794.  
  795.         Declarations in the language of the actions may be  included  in
  796.         both  the  auxiliary  definition  section and in the translation
  797.         section.   In  the  former  case,  these  declarations  will  be
  798.         external  to  the lexical analyser, and in the latter case, they
  799.         will be local to the lexical analyser (ie, static, or  automatic
  800.         storage).    Declaration  sections  consist  of  a  sequence  of
  801.         declarations surrounded by the special bracketing sequences '%{'
  802.         and '%}' (as in Yacc).  The characters within these brackets are
  803.         copied unchanged into  the  appropriate  spots  in  the  lexical
  804.         analyser  program  that  LEX writes.  The examples in appendix A
  805.         suggest how these might be used.
  806.  
  807.  
  808.  
  809.         3.0  Using Lex from C
  810.  
  811.              _____ ___ ____ _
  812.  
  813.  
  814.         The present version of LEX is intended for use with C;   and  it
  815.         is this usage which will be described here.
  816.  
  817.  
  818.  
  819.         3.1  The Function yylex()
  820.  
  821.              ___ ________ _______
  822.  
  823.  
  824.         The structure  of  LEX  programs  is  influenced  by  what  Yacc
  825.         requires of its lexical analyser.
  826.  
  827.         To begin with, the lexical analyser must be named  'yylex',  has
  828.         no  parameters,  and is expected to return a token number, where
  829.         that number is determined by Yacc.   The  token  number  for  an
  830.         Ascii  character  is  its  Ascii  value  (ie,  its  value as a C
  831.         character constant).  Named tokens,  defined  in  yacc  '%token'
  832.         statements,  have a number above 256, with the particular number
  833.         accessible through a Yacc-produced #define of  the  given  token
  834.         name as its number.  Yacc also allows 'yylex' to pass a value to
  835.         the Yacc  action  routines,  by  assigning  that  value  to  the
  836.         external 'yylval'.
  837.  
  838.         LEX thus provides a lexical  analyser  function  named  'yylex',
  839.         which interprets tables constructed by the LEX program returning
  840.  
  841.  
  842.  
  843.  
  844.  
  845.         A Lexical Analyser Generator                                     Pag
  846.  
  847.  
  848.         the token number returned by the actions  it  performs.   Values
  849.         assigned  to  lexval are available in 'yylval', so that use with
  850.         Yacc is straightforward.
  851.  
  852.         A value of zero is returned by 'yylex' at  end-of-file,  and  in
  853.         the absence of a return statement in an action, a non-zero value
  854.  
  855.                          ______
  856.         is returned.   If  computation  is  performed  entirely  by  the
  857.         lexical analyser, then a suitable main program would be
  858.  
  859.                 main()
  860.                    {
  861.                    while (yylex()) ;
  862.                    }
  863.  
  864.  
  865.  
  866.  
  867.         3.2  Serial Re-Use of yylex()
  868.  
  869.              ______ ______ __ _______
  870.  
  871.  
  872.         The  yylex()  function  contains  several  variables  which  are
  873.         statically  initialized  at  compile time.  Once yylex() sees an
  874.         EOF (-1) input character, it will continue to return  NULL.   If
  875.         yylex()  is  to  be  used inside a loop which processes multiple
  876.         files, it must be re-initialized at the beginning  of  each  new
  877.         file  with  a  call  to  the  LEX library routine llinit().  For
  878.         example (slightly extending the previous example):
  879.  
  880.                 main()
  881.                    {
  882.                    getfilelist();
  883.                    for(file = first; file != last; file = next)
  884.                       {
  885.                       llinit();
  886.                       while (yylex());
  887.                       }
  888.                    printf("All files done\n");
  889.                    }
  890.  
  891.         The call to llinit() is unnecessary if  yylex()  is  to  process
  892.         only one file, or is kept from seeing an EOF input character.
  893.  
  894.  
  895.  
  896.         3.3  The Lex Table File
  897.  
  898.              ___ ___ _____ ____
  899.  
  900.  
  901.         In the absence of instructions to the contrary (see below),  LEX
  902.         reads a given LEX language file, (from the standard input, if an
  903.         input file has not been specified) and produces a C program file
  904.         'lextab.c'  which  largely  consists  of  tables  which are then
  905.         interpreted by 'yylex()' (which is in  the  LEX  library).   The
  906.         actions  supplied  by  the user in each translation are combined
  907.         with a switch statement into a single function, which is  called
  908.  
  909.                ______
  910.         by  the table interpreter when a particular token is found.  The
  911.  
  912.  
  913.  
  914.  
  915.  
  916.         A Lexical Analyser Generator                                     Pag
  917.  
  918.  
  919.         contents of the program section of the LEX file are added at the
  920.         end  of  the  output  file (lextab.c by default).  Normally, LEX
  921.         also inserts the lines
  922.  
  923.                 #include <stdio.h>
  924.                 #include <lex.h>
  925.  
  926.         at the top of the file;  this causes  declarations  required  by
  927.         the  standard  I/O  library and by LEX to be included when the C
  928.         program is compiled.
  929.  
  930.  
  931.  
  932.         3.4  Analyzers Which Don't Use "Standard I/O"
  933.  
  934.              _________ _____ _____ ___ _________ ____
  935.  
  936.  
  937.         With  the  current  release,  LEX  supports  the  generation  of
  938.         analyzers  which  may be incorporated into programs which do not
  939.         use the "standard I/O" library.  By setting the "-s" switch,  as
  940.         shown  below, the generation of the "#include <stdio.h>" line is
  941.         supressed.  All references to standard I/O  specific  files  and
  942.         stdio.h  have  been removed from the LEX library (described in a
  943.         later section), with the  exception  of  lexgetc(),  lexerror(),
  944.         mapch() and lexecho(), which are standard I/O dependent.
  945.  
  946.         The declaration of yylex()'s input file iov pointer "lexin"  now
  947.         resides  in LEXGET.C (lexgetc()).  The code which defaults lexin
  948.         to stdin has been moved from yylex() to the table file.  yylex()
  949.         now  calls  the  routine  llstin(),  which is generated into the
  950.         table file.  There are no longer any hardwired references to the
  951.         variable   "lextab",  the  default  table  name.   Instead,  LEX
  952.         generates a call to lexswitch() in llstin(),  which  initializes
  953.         yylex()  to use the table whose name was given in a "-t" or "-e"
  954.         option in LEX's command line.  If neither was given, the default
  955.         name  "lextab" is used.  Once the initial table has been set up,
  956.         further automatic calls to lexswitch() are  supressed,  allowing
  957.         the user to manually switch tables as before.
  958.  
  959.         In addition, If the "-s" switch is not given (i.e.,  normal  use
  960.         with  standard  I/O), llstin() defaults lexin to stdin.  If "-s"
  961.         is given, llstin() is generated to do the lexswitch()  mentioned
  962.         above  only.  In any case, yylex() contains no references to the
  963.         standard I/O system.
  964.  
  965.         What all of this means is that under normal operation, you won't
  966.         notice  any  change  in LEX's characteristics.  In addition, you
  967.         may use the "-e" ("easy") switch, which will generate a C output
  968.         file  and  LEX tables which (conveniently) have the same name as
  969.         the input file, and everything will get  set  up  automagically.
  970.         If  you  specify the "-s" switch, the table file will contain no
  971.         references to the standard I/O package, and you may use  any  of
  972.         the  lexlib  routines  except  lexgetc(), lexerror(), mapch() or
  973.         lexecho().
  974.  
  975.         Don't forget that you  must  supply  your  own  startup  routine
  976.  
  977.  
  978.  
  979.  
  980.  
  981.  
  982.  
  983.         A Lexical Analyser Generator                                     P
  984.  
  985.  
  986.         "$$main"  if  you  do not want the standard I/O library.  With a
  987.         bit of care in this regard, it will be  possible  to  link  your
  988.         program  with the C library without dragging in any I/O modules.
  989.         This prevents your having to build another library in  order  to
  990.         access  non-I/O  library  functions.  Just make the reference to
  991.         the C library the last one given to the linker or taskbuilder so
  992.         that  only  those routines which have not already been found are
  993.         pulled from CLIB.
  994.  
  995.  
  996.                                       NOTE
  997.  
  998.             Programs that use LEX-generated analyzers and do not use
  999.             the standard I/O package must supply their own lexgetc()
  1000.             and lexerror() routines.  Failure to do so  will  result
  1001.             in undefined globals.
  1002.  
  1003.  
  1004.  
  1005.  
  1006.  
  1007.         3.5  Operating LEX
  1008.  
  1009.              _________ ___
  1010.  
  1011.  
  1012.         LEX normally reads the grammar from the standard input,  writing
  1013.         the  C  program  to  the  file  'lextab.c'.   It  may be further
  1014.         controlled by using the following flags upon invocation:
  1015.  
  1016.                 -i filename     The grammar is read from 'filename'.
  1017.  
  1018.                 -o filename     The analyser is written to 'filename'.
  1019.  
  1020.                 -t tablename    The default  finite-state  automaton  is
  1021.                                 named  lextab  (and  it  is, by default,
  1022.                                 written to  file  'lextab.c').   The  -t
  1023.                                 switch  causes the internal tables to be
  1024.                                 named 'tablename' and, if the -o  switch
  1025.                                 is    not   given,   written   to   file
  1026.                                 'tablename.c'.  This is necessary if the
  1027.                                 processor-switching         capabilities
  1028.                                 described in a later section are  to  be
  1029.                                 used.
  1030.  
  1031.                 -e name         "Easy"  command  line.    "-e name"   is
  1032.                                 equivalent to typing
  1033.  
  1034.                                    -i name.LXI -o name.C -t name
  1035.  
  1036.                                 Do not  include  device  names  or  file
  1037.                                 extensions on the "easy" command line.
  1038.  
  1039.                 -v [filename]   Internal state information is written to
  1040.                                 'filename.'   If   not   present,  state
  1041.                                 information   is   written    to    file
  1042.                                 'lex.out.'
  1043.  
  1044.  
  1045.  
  1046.  
  1047.  
  1048.  
  1049.  
  1050.         A Lexical Analyser Generator                                     P
  1051.  
  1052.  
  1053.                 -d              Enable various debugging printouts.
  1054.  
  1055.                 -s              Generate analyzer without references  to
  1056.                                 standard I/O
  1057.  
  1058.  
  1059.         The command line  for  compilation  of  the  table  file  should
  1060.         contain no surprises:
  1061.  
  1062.                 cc -c -O lextab.c       (on Unix)
  1063.  
  1064.                 xcc lextab -a           (on Dec operating systems)
  1065.  
  1066.         but when one is producing  the  running  program,  one  must  be
  1067.         careful to include the necessary libraries.  On Unix, the proper
  1068.         sequence is:
  1069.  
  1070.                 cc userprog.o lextab.o -ll -lS
  1071.  
  1072.         The '-ll'  causes  the  LEX  library  (described  below)  to  be
  1073.         searched,  and  the  '-lS' causes the Standard I/O library to be
  1074.         used;  both libraries are required.  If Yacc is  used  as  well,
  1075.         the  library  '-ly'  should  be  included before the '-ll'.  The
  1076.  
  1077.                                                   ______
  1078.         actual order and content of the rest  of  the  command  line  is
  1079.         determined by the user's own requirements.
  1080.  
  1081.         If using the Decus C compiler, the lexical analyser built by LEX
  1082.         is linked with c:lexlib.
  1083.  
  1084.         The complete process (assuming the  Decus  compiler  running  on
  1085.         RSTS/E in RT11 mode) is thus:
  1086.  
  1087.                 mcr lex -i grammar.lxi -o grammar.c     ! Build analyser
  1088.                 cc grammar                              ! Compile the
  1089.                 as grammar                              ! grammar table
  1090.                 link out=in,grammar,c:lexlib,c:suport,c:clib/b:2000
  1091.  
  1092.  
  1093.  
  1094.  
  1095.         4.0  The Lex Library
  1096.  
  1097.              ___ ___ _______
  1098.  
  1099.  
  1100.         All programs using grammars generated  by  LEX  must  be  linked
  1101.         together  with  the LEX library.  On Unix, this is '/lib/libl.a'
  1102.         (or '-ll' on the cc command line) and on DEC operating  systems,
  1103.         C:LEXLIB  (LB:[1,1]LEX.OLB for RSX).  It contains routines which
  1104.         are either essential or merely useful  to  users  of  LEX.   The
  1105.         essential  routines  include  a  routine to obtain a copy of the
  1106.         current token, and a routine to switch to  a  different  set  of
  1107.         scanning  tables.  Routines of the second, useful, class perform
  1108.         functions which might well be written by the user  himself,  but
  1109.         are  there  to  save  him  the  bother;   including a routine to
  1110.         process various forms of comments and  a  routine  to  transform
  1111.         numbers  written  in arbitrary bases.  Both sets of routines are
  1112.  
  1113.  
  1114.  
  1115.  
  1116.  
  1117.  
  1118.         A Lexical Analyser Generator                                     Pa
  1119.  
  1120.  
  1121.         expected to grow as LEX sees use.
  1122.  
  1123.         Those functions which  produce  diagnostics  do  so  by  calling
  1124.         lexerror(), which is called as
  1125.  
  1126.                 lexerror(string, arg1, ..., argN)
  1127.  
  1128.         and is expected to write its arguments (likely using the "remote
  1129.         format"  facility  of  the  fprintf()  function),  followed by a
  1130.         newline, on  some  output  stream.   A  Lexerror()  function  is
  1131.         included  in  the LEX library, but a user is free to include his
  1132.         own.  The routine in the LEX library is standard I/O specific.
  1133.  
  1134.  
  1135.                                       NOTE
  1136.  
  1137.             The VAX/VMS native C library  does  not  support  remote
  1138.             formats.   The  Lexerror  function  in  the  LEX library
  1139.             conditionally compiles to support a call  to  lexerror()
  1140.             with  only  an error message string.  Remote formats are
  1141.             supported under Decus C.  Learn to use  them,  they  are
  1142.             very nice!
  1143.  
  1144.  
  1145.  
  1146.  
  1147.  
  1148.         4.0.1  Comment -- skip over a comment -
  1149.  
  1150.                _______ __ ____ ____ _ _______
  1151.  
  1152.                 comment(delim)
  1153.                 char delim[];
  1154.  
  1155.         Comment() may be called by a translation when  the  sequence  of
  1156.         characters which mark the start of a comment in the given syntax
  1157.         has been recognised by LEX.  It takes a string which  gives  the
  1158.         sequence  of  characters  which  mark  the end of a comment, and
  1159.         skips over characters in the input stream until this sequence is
  1160.         found.   Newlines  found  while  skipping  characters  cause the
  1161.         external 'yyline' to be incremented;  an unexpected  end-of-file
  1162.         produces  a  suitable diagnostic.  Thus, 'comment("*/")' matches
  1163.         C-style comments, and 'comment("\n")' matches as-style comments.
  1164.         There  are  other  methods  of  handling  comments  in LEX;  the
  1165.         comment() function is usually the best with regard to both space
  1166.         and time.
  1167.  
  1168.  
  1169.  
  1170.         4.0.2  Gettoken -- obtain a copy of token -
  1171.  
  1172.                ________ __ ______ _ ____ __ _____
  1173.  
  1174.                 gettoken(buf, sizeof(buf))
  1175.                 char buf[];
  1176.  
  1177.         Gettoken() takes the address of a character buffer, and its size
  1178.         in bytes, and copies the token most recently matched by LEX into
  1179.         the buffer.  A null byte is added to mark the end of  the  token
  1180.  
  1181.  
  1182.  
  1183.  
  1184.  
  1185.  
  1186.         A Lexical Analyser Generator                                     Pa
  1187.  
  1188.  
  1189.         in  the  buffer, but, as null bytes are legitimate characters to
  1190.         LEX, the true length of the token is returned by gettoken().
  1191.  
  1192.         For example, the following function calls lexlength() to  obtain
  1193.         the  length  of a token.  It then calls the storage allocator to
  1194.         allocate sufficient storage for the token and copies  the  token
  1195.         into the allocated area.
  1196.  
  1197.                 char *
  1198.                 save()
  1199.                 /*
  1200.                  * Save current token, return a pointer to it
  1201.                  */
  1202.                 {
  1203.                         register char   *tbuffer;
  1204.                         register int    len;
  1205.                         register char   *tend;
  1206.                         extern char     *token();
  1207.                         extern char     *copy();
  1208.  
  1209.                         len = lexlength() + 1;
  1210.                         if (tbuffer = malloc(len)) == NULL)
  1211.                                 error("No room for token");
  1212.                         gettoken(tbuffer, len);
  1213.                         return(tbuffer);
  1214.                 }
  1215.  
  1216.  
  1217.  
  1218.  
  1219.         4.0.3  Integ -- long integer, any base -
  1220.  
  1221.                _____ __ ____ ________ ___ ____
  1222.  
  1223.                 long
  1224.                 integ(nptr, base)
  1225.                 char *nptr;
  1226.  
  1227.         Integ() converts the Ascii string at 'nptr' into a long integer,
  1228.         which  it  returns.   Conversion  stops  at the first non-digit,
  1229.         where the digits are  taken  from  the  class  "[0-9a-zA-Z]"  as
  1230.         limited by the given 'base'.  Integ() does not understand signs,
  1231.         nor are blanks or tabs allowed in the string.
  1232.  
  1233.  
  1234.  
  1235.         4.0.4  Lexchar -- steal character -
  1236.  
  1237.                _______ __ _____ _________
  1238.  
  1239.                 lexchar()
  1240.  
  1241.         Lexchar() returns the next character from the LEX input  stream.
  1242.         (This  means  that  LEX  will  no  longer  see  it.)  LEX uses a
  1243.         look-ahead buffer to handle complex languages, and this function
  1244.         takes this into account.
  1245.  
  1246.  
  1247.  
  1248.  
  1249.  
  1250.  
  1251.  
  1252.  
  1253.  
  1254.         A Lexical Analyser Generator                                    
  1255.  
  1256.  
  1257.         4.0.5  Lexecho -- write token to a file (STDIO ONLY) -
  1258.  
  1259.                _______ __ _____ _____ __ _ ____ ______ _____
  1260.  
  1261.                 lexecho(fp);
  1262.                 FILE *fp;
  1263.  
  1264.         Lexecho() may be called by a LEX action  routine  to  write  the
  1265.         current token to a specified file.
  1266.  
  1267.  
  1268.                                       NOTE
  1269.  
  1270.             Programs using analyzers built with  LEX's  "-s"  switch
  1271.             must supply their own lexecho() function if needed.
  1272.  
  1273.  
  1274.  
  1275.  
  1276.  
  1277.         4.0.6  Lexgetc -- supply characters to yylex (STDIO ONLY) -
  1278.  
  1279.                _______ __ ______ __________ __ _____ ______ _____
  1280.  
  1281.                 lexgetc()
  1282.  
  1283.         Lexgetc() is called by the lexical analyser to obtain characters
  1284.         from  its input stream.  The version in the library is dependent
  1285.         on the standard I/O package, and is:
  1286.  
  1287.                 FILE *lexin;    /* Declare iov address locally */
  1288.                 lexgetc()
  1289.                 {
  1290.                         return(getc(lexin));
  1291.                 }
  1292.  
  1293.         If lexin is NULL when yylex() is entered, it will be assigned to
  1294.         stdin.   This  is done by yylex() calling the function llstin(),
  1295.         which is generated in the table file.  Unless the "-s" switch is
  1296.         given  to  LEX,  the llstin() function assigns lexin to stdin if
  1297.         lexin is NULL.  If the  "-s"  switch  was  given,  the  llstin()
  1298.         routine  is  a  no-op.   The user may provide his own version of
  1299.         lexgetc() to pre-process the data to the lexical  analyser.   An
  1300.         example of this is shown in the appendix.
  1301.  
  1302.  
  1303.                                       NOTE
  1304.  
  1305.             Programs using analyzers built with  LEX's  "-s"  switch
  1306.             must  supply  their  own lexgetc() function, and "lexin"
  1307.             has no meaning in this context.
  1308.  
  1309.  
  1310.  
  1311.  
  1312.  
  1313.  
  1314.  
  1315.  
  1316.  
  1317.  
  1318.  
  1319.  
  1320.  
  1321.  
  1322.         A Lexical Analyser Generator                                 
  1323.  
  1324.  
  1325.         4.0.7  Lexlength -- return length of a token. -
  1326.  
  1327.                _________ __ ______ ______ __ _ ______
  1328.  
  1329.                 lexlength();
  1330.  
  1331.         Lexlength() may be called by a LEX action routine to obtain  the
  1332.         length  of  the  current  token in bytes.  An example of this is
  1333.         shown in the description of gettoken().
  1334.  
  1335.  
  1336.  
  1337.         4.0.8  Lexpeek -- examine character -
  1338.  
  1339.                _______ __ _______ _________
  1340.  
  1341.                 lexpeek()
  1342.  
  1343.         Lexpeek() performs a function similar to that of Lexchar(),  but
  1344.         does  not  have  the  side-effect of removing the character from
  1345.         LEX's view.
  1346.  
  1347.  
  1348.  
  1349.         4.0.9  Lexswitch -- switch scanning tables -
  1350.  
  1351.                _________ __ ______ ________ ______
  1352.  
  1353.                 struct lextab *
  1354.                 lexswitch(newtb)
  1355.                 struct lextab *newtb;
  1356.  
  1357.         Lexswitch() is called to cause LEX to use a  different  scanning
  1358.         table;  it returns a pointer to the one previously in use.  This
  1359.         facility is useful if  certain  objects  of  the  language  (eg,
  1360.         strings  in  C) have a fairly complicated structure of their own
  1361.         which cannot be handled within the translation  section  of  the
  1362.         LEX description of the larger language.
  1363.  
  1364.  
  1365.  
  1366.         4.0.10  Llinit -- Reinitialize yylex() -
  1367.  
  1368.                 ______ __ ____________ _______
  1369.  
  1370.                 llinit()
  1371.  
  1372.         Llinit() is a function which resets the state of yylex() to it's
  1373.         cold-start   condition.   Several  of  yylex()'s  variables  are
  1374.         initialized at compile time, and must be reinitialized if it  is
  1375.         to  be serially re-used.  An example of this is where yylex() is
  1376.         repeatedly called inside a loop which processes  multiple  input
  1377.         files.  Each time a new file is started, llinit() must be called
  1378.         before the first call to yylex() for the new file.
  1379.  
  1380.  
  1381.  
  1382.  
  1383.  
  1384.  
  1385.  
  1386.  
  1387.  
  1388.  
  1389.  
  1390.  
  1391.  
  1392.         A Lexical Analyser Generator                                
  1393.  
  1394.  
  1395.         4.0.11  Mapch -- Handle C escapes within strings (STDIO ONLY) -
  1396.  
  1397.                 _____ __ ______ _ _______ ______ _______ ______ _____
  1398.  
  1399.                 int mapch(delim, esc)
  1400.                 char delim;
  1401.                 char esc;
  1402.  
  1403.         Mapch() is a function which handles C "escape"  characters  such
  1404.         as "\n" and "\nnn".  It will scan off the entire escape sequence
  1405.         and return the equivalent ASCII code as an integer.  It is meant
  1406.         for  use  with  YACC while scanning quoted strings and character
  1407.         constants.
  1408.  
  1409.         If it encounters EOF while  scanning,  it  calls  lexerror()  to
  1410.         print  an  error message warning of "Unterminated string".  If a
  1411.         normal character is  read,  it  returns  the  ASCII  value.   If
  1412.         "delim"  (usually " or ') is read, it returns EOF.  If a newline
  1413.         (ASCII linefeed) is read, it increments the global "yyline"  and
  1414.         calls itself recursively for the next line of input.  It may use
  1415.  
  1416.         _____ ______ ___________
  1417.         the ungetc() function to back up in the input stream.
  1418.  
  1419.  
  1420.                                       NOTE
  1421.  
  1422.             This routine is very application-specific for use by LEX
  1423.             and  YACC  when  they  are working together.  You should
  1424.             read the code in MAPCH.C before using this function.
  1425.  
  1426.  
  1427.  
  1428.  
  1429.  
  1430.         4.0.12  Token -- get pointer to token -
  1431.  
  1432.                 _____ __ ___ _______ __ _____
  1433.  
  1434.                 char *
  1435.                 token(end_pointer)
  1436.                 char **end_pointer;
  1437.  
  1438.         Token() locates the first byte of the current token and  returns
  1439.         its  address.   It  takes  an argument which is either NULL or a
  1440.         pointer to a character pointer;  if the latter, that pointer  is
  1441.         set  to  point  to  the  byte after the last byte of the current
  1442.  
  1443.                                       _____
  1444.         token.  Token() is slightly faster,  and  more  convenient  than
  1445.         gettoken()  for  those  cases where the token is only one or two
  1446.         bytes long.
  1447.  
  1448.  
  1449.  
  1450.  
  1451.         5.0  Error Detection and Recovery
  1452.  
  1453.              _____ _________ ___ ________
  1454.  
  1455.  
  1456.         If a character is detected in the input stream which  cannot  be
  1457.         added  to  the  last-matched  string,  and  which cannot start a
  1458.         string, then that character is considered illegal by  LEX.   LEX
  1459.  
  1460.  
  1461.  
  1462.  
  1463.  
  1464.         may be instructed to return a special 'error' token, or to write
  1465.  
  1466.  
  1467.  
  1468.  
  1469.  
  1470.  
  1471.  
  1472.  
  1473.  
  1474.  
  1475.  
  1476.  
  1477.  
  1478.  
  1479.  
  1480.  
  1481.  
  1482.  
  1483.  
  1484.  
  1485.  
  1486.  
  1487.  
  1488.  
  1489.  
  1490.  
  1491.  
  1492.  
  1493.  
  1494.  
  1495.  
  1496.  
  1497.  
  1498.  
  1499.  
  1500.  
  1501.  
  1502.  
  1503.  
  1504.  
  1505.  
  1506.  
  1507.  
  1508.  
  1509.  
  1510.  
  1511.  
  1512.  
  1513.  
  1514.  
  1515.  
  1516.  
  1517.  
  1518.  
  1519.  
  1520.  
  1521.  
  1522.  
  1523.  
  1524.  
  1525.  
  1526.  
  1527.  
  1528.  
  1529.  
  1530.         A Lexica
  1531.  
  1532.  
  1533.         a diagnostic with lexerror().  At present,  the  former  is  the
  1534.         default action.
  1535.  
  1536.         The token LEXERR is a special value which is recognised by Yacc,
  1537.         and causes it to start its own error recovery.  It is defined by
  1538.         the header file lex.h for use by other programs.
  1539.  
  1540.         Often, it makes more sense to simply type a suitable diagnostic,
  1541.         and  continue by ignoring the offending character.  It is fairly
  1542.         easy to cause  LEX  to  do  this,  by  including  the  auxiliary
  1543.         definition:
  1544.  
  1545.                 illegal = [\0-\377];
  1546.  
  1547.         which defines a  character  class  "illegal"  which  is  handled
  1548.         specially  by LEX.  If the character that is causing the trouble
  1549.         is a member of that character class (and  in  the  example,  all
  1550.         characters  are),  then  LEX will write a diagnostic, and ignore
  1551.         it;  otherwise, it will return the special token LEXERR
  1552.  
  1553.         More comprehensive  techniques  may  be  added  as  they  become
  1554.         apparent.
  1555.  
  1556.  
  1557.  
  1558.         6.0  Ambiguity and Look-ahead
  1559.  
  1560.              _________ ___ __________
  1561.  
  1562.         Many computer languages have ambiguous grammars in that an input
  1563.         token  may represent more than one logical entity.  This section
  1564.         discusses the  way  in  which  grammars  built  by  LEX  resolve
  1565.         ambiguous  input,  as  well  as  a way for the grammar to assign
  1566.         unique meaning to a token by looking ahead in the input stream.
  1567.  
  1568.  
  1569.  
  1570.         6.1  Resolving Ambiguities
  1571.  
  1572.              _________ ___________
  1573.  
  1574.  
  1575.         A LEX program may be ambiguous, in the sense that  a  particular
  1576.         input  string  or  strings  might  be  matched  by  the  regular
  1577.         expression of more than one translation.  Consider,
  1578.  
  1579.                 [a-z] { putchar(*token(NULL)); }
  1580.                 aaa*  { printf("abc"); }
  1581.  
  1582.         in which the string 'aa' is matched by both regular  expressions
  1583.         (twice  by the first, and once by the second).  Also, the string
  1584.         'aaaaaa' may be matched in many  different  ways.   LEX  has  to
  1585.         decide    somehow    which    actions   should   be   performed.
  1586.         (Alternatively, it could produce a diagnostic, and give up.   As
  1587.         it happens, LEX never does this.)
  1588.  
  1589.         Consider a second example,
  1590.  
  1591.                 letter = [a-z];
  1592.  
  1593.  
  1594.  
  1595.  
  1596.  
  1597.  
  1598.         A Lexical Analyser Generator                                     Pa
  1599.  
  1600.  
  1601.                 %%
  1602.                 A(letter)*      { return(1); }
  1603.                 AB(letter)*     { return(2); }
  1604.  
  1605.         which attempts to distinguish sequences of  letters  that  begin
  1606.         with 'a' from similar sequences that begin with 'ab'.  These two
  1607.         examples illustrate two different kinds of  ambiguity,  and  the
  1608.         following indicates how LEX resolves these.
  1609.  
  1610.         In the first example, it seems likely that  the  intent  was  to
  1611.         have both 'aa' and 'aaaaaa' perform the second action, while all
  1612.         single letters 'a' cause the first action to be performed.   LEX
  1613.         does  this  by  ensuring  that  the longest possible part of the
  1614.         input stream will be used to determine the match.  Thus,
  1615.  
  1616.                 <       { return(LESS); }
  1617.                 <=      { return(LESSEQ); }
  1618.  
  1619.         or
  1620.  
  1621.                 digit(digit)*           { return(NUMBER); }
  1622.                 letter(letter|digit)*   { return(NAME); }
  1623.  
  1624.         would work as one might expect.
  1625.  
  1626.         In the second example, the longest-string need not work.  On the
  1627.         string  "abb9",  either  action could apply, and so another rule
  1628.         must be followed.  This states that if, after the longest-string
  1629.         rule  has  been  applied,  there  remains an ambiguity, then the
  1630.         action which appears first in the LEX  program  file  is  to  be
  1631.         performed.   As the second example is written, the second action
  1632.         will never be performed.  It would have been written as:
  1633.  
  1634.                 letter = [a-z];
  1635.                 %%
  1636.                 AB(letter)*     { return(1); }
  1637.                 A(letter)*      { return(2); }
  1638.  
  1639.         The two rules together completely determine a string.
  1640.  
  1641.         At present, LEX produces  no  diagnostic  in  either  case;   it
  1642.         merely  applies  the  rules  and  proceeds.   In  the case where
  1643.         priority is given to the first-appearing rule,  it  might  be  a
  1644.         good idea to produce a diagnostic.
  1645.  
  1646.  
  1647.  
  1648.         6.2  Look-ahead
  1649.  
  1650.              __________
  1651.  
  1652.  
  1653.         Some facility for looking ahead in the input stream is sometimes
  1654.         required.   (This  facility  might also be regarded as a way for
  1655.         the  programmer  to  more  closely   control   LEX's   ambiguity
  1656.         resolution  process.)  For example, in C, a name followed by "("
  1657.         is to be contextually declared as an external function if it  is
  1658.  
  1659.  
  1660.  
  1661.  
  1662.  
  1663.  
  1664.  
  1665.         A Lexical Analyser Generator                                     P
  1666.  
  1667.  
  1668.         otherwise undefined.
  1669.  
  1670.         In Pascal, look-ahead is required to determine that
  1671.  
  1672.                 123..1234
  1673.  
  1674.         is an  integer  123,  followed  by  the  subrange  symbol  "..",
  1675.         followed  by  the  integer 1234, and not simply two real numbers
  1676.         run together.
  1677.  
  1678.         In both of these cases, the desire is to look ahead in the input
  1679.         stream  far  enough  to  be able to make a decision, but without
  1680.         losing tokens in the process.
  1681.  
  1682.         A special  form  of  regular  expression  is  used  to  indicate
  1683.         look-ahead:
  1684.  
  1685.                 re1 '/' re2     '{' action '}'
  1686.  
  1687.         where 're1' and 're2' are regular  expressions.   The  slash  is
  1688.         treated  as  concatenation for the purposes of matching incoming
  1689.         characters;  thus both 're1' and 're2' must match adjacently for
  1690.         the  action  to  be performed.  'Re1' indicates that part of the
  1691.         input string which is the token  to  be  returned,  while  're2'
  1692.         indicates  the context.  The characters matched by 're2' will be
  1693.         re-read at the next call to yylex(), and broken into tokens.
  1694.  
  1695.         Note that you cannot write:
  1696.  
  1697.                 name = re1 / re2;
  1698.  
  1699.         The look-ahead operator must be part of the  rule.   It  is  not
  1700.         valid in definitions.
  1701.  
  1702.         In the first example, the look-ahead operator would be used as:
  1703.  
  1704.                 name / "(" {
  1705.                                 if (name undefined)
  1706.                                         declare name a global function;
  1707.                         }
  1708.                 name    {       /* usual processing for identifiers */
  1709.                         }
  1710.  
  1711.         In the second example, the range construction would be parsed as
  1712.         follows:
  1713.  
  1714.                 digit   = [0-9];
  1715.                 int     = digit(digit)*;
  1716.                 %%
  1717.                 int / ".." int  { /* Start of a range */
  1718.                 ".." int        { /* End of a range   */
  1719.  
  1720.  
  1721.         Note that right-context is  not  sufficient  to  handle  certain
  1722.         types of ambiguity, as is found in several places in the Fortran
  1723.  
  1724.  
  1725.  
  1726.  
  1727.  
  1728.  
  1729.  
  1730.  
  1731.         A Lexical Analyser Generator                                     
  1732.  
  1733.  
  1734.         language.  For example,
  1735.  
  1736.                 do i = 1        Is an assignment statement
  1737.                 do i = 1, 4     Is a DO statement
  1738.  
  1739.         It is not sufficient to use right-context scanning to  look  for
  1740.         the   comma,   as   it   may   occur   within   a  parenthesized
  1741.         sub-expression:
  1742.  
  1743.                 do i = j(k,l)   Is an assignment statement
  1744.  
  1745.         In Fortran, similar problems exist for IF and FORMAT statements,
  1746.         as  well  as counted (Hollerith) string constants.  All of these
  1747.         require a more  powerful  grammar  than  is  possible  with  LEX
  1748.         regular-expressions.
  1749.  
  1750.  
  1751.  
  1752.         7.0  Multiple Scanning Tables; Processor Switching
  1753.  
  1754.              ________ ________ _______ _________ _________
  1755.  
  1756.  
  1757.         Even a fairly simple syntax may be difficult, or impossible,  to
  1758.         describe  and  process  with  a  single set of translations.  An
  1759.         example of this may be found in C, where strings, which are part
  1760.         of  the language, have quite a different structure, and in order
  1761.         to process them, either a function must be  called  which  reads
  1762.         and parses the input stream for itself, or some mechanism within
  1763.         LEX must be invoked to  cause  a  (usually  massive)  change  of
  1764.         state.
  1765.  
  1766.         LEX does provide such a facility, which is known, after AED,  as
  1767.         'processor  switching'.   Yylex()  locates  its tables through a
  1768.         pointer;  if one simply changes the pointer to point  at  a  new
  1769.         set  of  tables,  one  will have effected the required change of
  1770.         state.  The LEX library function lexswitch(), which is described
  1771.         elsewhere  in  this guide, arranges to do this;  it also returns
  1772.         the old value of the pointer so that it may  be  restored  by  a
  1773.         later  call  to  Lexswitch.   Thus, scanning environments may be
  1774.         stacked, or not, as the user requires.
  1775.  
  1776.  
  1777.  
  1778.         7.1  Creation of a Processor
  1779.  
  1780.              ________ __ _ _________
  1781.  
  1782.  
  1783.         It should be clear that if all the tables produced by LEX from a
  1784.         user's translation file have the same name, someone (the loader)
  1785.         is bound to object.  Some method must be provided to change  the
  1786.         name of the table.
  1787.  
  1788.         This is done by an option flag to the LEX command:
  1789.  
  1790.                 -t name
  1791.  
  1792.         will cause the scanning table to be declared as
  1793.  
  1794.  
  1795.  
  1796.  
  1797.  
  1798.  
  1799.         A Lexical Analyser Generator                                     Pa
  1800.  
  1801.  
  1802.                 struct lextab name;
  1803.  
  1804.         so that it may be passed to LEXswitch:
  1805.  
  1806.                 lexswitch(&name);
  1807.  
  1808.         LEX also writes the program file to  the  file  "name.c"  rather
  1809.         than to "lextab.c."
  1810.  
  1811.  
  1812.                                       NOTE
  1813.  
  1814.             If you use the "easy"  command  line  ("-e  name")  when
  1815.             running  LEX,  the  output  file  and  table  names will
  1816.             correspond nicely.  Re-read the section on operating LEX
  1817.             for more details.
  1818.  
  1819.  
  1820.  
  1821.  
  1822.  
  1823.         8.0  Conclusion
  1824.  
  1825.              __________
  1826.  
  1827.  
  1828.         LEX seems to handle most lexical analysis tasks easily.  Indeed,
  1829.         LEX   may  be  more  generally  used  to  write  commands  of  a
  1830.         text-processing nature;  an example of such usage may  be  found
  1831.         in  an  appendix.  LEX programs are far easier to write than the
  1832.         equivalent  C  programs,  and  generally  consume   less   space
  1833.         (although  there  is  an  initial  overhead for the more general
  1834.         table-interpreter  program).   The  encoding  suggested  in  [4]
  1835.         achieves   a  reasonable  compromise  between  table  size,  and
  1836.         scanning speed.  Certainly lexical analysers  are  less  tedious
  1837.         and time-consuming to write.
  1838.  
  1839.         It is expected that most change in the future  will  be  through
  1840.         additions  to  the  LEX  library.   The  LEX language may change
  1841.         slightly to accomodate common kinds  of  processing  (eg,  break
  1842.         characters),  or  to  extend  its range of application.  Neither
  1843.         kind of change should affect existing LEX programs.
  1844.  
  1845.         LEX produces tables and programs for the C language.  The tables
  1846.         are  in a very simple (and stylised) format, and when LEX copies
  1847.         the action routines or the program section, the  code  might  as
  1848.         well  be Fortran for all it cares.  One could write Unix filters
  1849.         to  translate  the  very  simple  C  format  tables  into  other
  1850.         languages,  allowing  LEX  to  be  used  with a larger number of
  1851.         languages, with little extra development  cost.   This  seems  a
  1852.         likely future addition.
  1853.  
  1854.         Because of the look-ahead necessary to  implement  the  "longest
  1855.         string  match"  rule, LEX is unsuitable for interactive programs
  1856.         whose overall structure is:
  1857.  
  1858.                 for (;;) {
  1859.  
  1860.  
  1861.  
  1862.  
  1863.  
  1864.  
  1865.  
  1866.         A Lexical Analyser Generator                                     P
  1867.  
  1868.  
  1869.                         prompt_user();
  1870.                         get_input();
  1871.                         process();
  1872.                         print_output();
  1873.                 }
  1874.  
  1875.         If these are rewritten as LEX-generated grammars, the user  will
  1876.         be  confused  by the fact the second input datum must be entered
  1877.         before the first is processed.  It is  possible  to  solve  this
  1878.         dilemna   by   rewriting   function   lexgetc()   to  return  an
  1879.         "end-of-line" character until processing is  complete  for  that
  1880.         line.  An example is shown in the Appendix.
  1881.  
  1882.  
  1883.  
  1884.         9.0  Acknowledgements
  1885.  
  1886.              ________________
  1887.  
  1888.  
  1889.         LEX  is  based  on  a  processor  of  the  same  name  at   Bell
  1890.         Laboratories,   which  also  runs  under  Unix  [3],  and,  more
  1891.         distantly, on AED-0 [1].  This version of LEX was based  on  the
  1892.         description  and suggestions of [4], although the implementation
  1893.         differs significantly in a number of ways.
  1894.  
  1895.  
  1896.  
  1897.         10.0  References
  1898.  
  1899.               __________
  1900.  
  1901.  
  1902.              1. Johnson,  W.L.,  et.   al.,  "Automatic  generation   of
  1903.                 efficient   lexical   analysers   using   finite   state
  1904.                 techniques", CACM Vol.  11, No.  12, pp.  805-813, 1968.
  1905.  
  1906.              2. Johnson, S.C., "Yacc -- Yet Another  Compiler-Compiler",
  1907.                 CSTR-32,  Bell  Telephone Laboratories, Murray Hill, New
  1908.                 Jersey, 1974.
  1909.  
  1910.              3. Lesk,  M.E.,  "Lex  -  a  lexical  analyser  generator",
  1911.                 CSTR-39,  Bell  Telephone Laboratories, Murray Hill, New
  1912.                 Jersey, 1975.
  1913.  
  1914.              4. Aho, A.V., Ullman, J.D., Principles of Compiler  Design,
  1915.  
  1916.                                          __________ __ ________  _______
  1917.                 Addison-Wesley, Don Mills, Ontario, 1977.
  1918.  
  1919.  
  1920.  
  1921.  
  1922.  
  1923.  
  1924.  
  1925.  
  1926.  
  1927.  
  1928.  
  1929.  
  1930.  
  1931.  
  1932.  
  1933.  
  1934.  
  1935.  
  1936.  
  1937.  
  1938.  
  1939.  
  1940.  
  1941.  
  1942.  
  1943.  
  1944.  
  1945.  
  1946.  
  1947.                                    APPENDIX A
  1948.  
  1949.                                LEX SOURCE GRAMMAR
  1950.  
  1951.  
  1952.  
  1953.         The following is a  grammar  of  LEX  programs  which  generally
  1954.         follows  Bacus-Naur  conventions.  In the rules, "||" stands for
  1955.         alternation (choose one  or  the  other).   Other  graphic  text
  1956.         stands  for  itself.   Several  grammar  elements  have  special
  1957.         meaning:
  1958.  
  1959.                 <anything>      Any text  not  including  the  following
  1960.                                 grammar  element  (either  a  literal or
  1961.                                 end-of-file).
  1962.  
  1963.                 <nothing>       Nothing  --  used  for   optional   rule
  1964.                                 elements.
  1965.  
  1966.                 <name>          A variable name.
  1967.  
  1968.                 <char_class>    A character class specifier.
  1969.  
  1970.                 <string>        A string (text inclosed in '"').
  1971.  
  1972.                 <EOF>           The end of the input file.
  1973.  
  1974.         This grammar was  abstracted  from  the  Yacc  grammar  used  to
  1975.         describe LEX.
  1976.  
  1977.                 program :==             aux_section trans_section
  1978.  
  1979.                 aux_section ::=         auxiliaries %%
  1980.                                 ||      %%
  1981.  
  1982.                 auxiliaries ::=         auxiliaries aux_def
  1983.                                 ||      aux_def
  1984.  
  1985.                 aux_def ::=             name_def = reg_exp ;
  1986.                                 ||      %{ <anything> %}
  1987.  
  1988.                 name_def ::=            <name>
  1989.  
  1990.                 reg_exp ::=             <char_class>
  1991.                                 ||      <string>
  1992.                                 ||      <name>
  1993.  
  1994.  
  1995.  
  1996.  
  1997.  
  1998.  
  1999.  
  2000.  
  2001.         A Lexical Analyser Generator                                    P
  2002.         LEX Source Grammar
  2003.  
  2004.  
  2005.                                 ||      reg_exp *
  2006.                                 ||      reg_exp | reg_exp
  2007.                                 ||      reg_exp  reg_exp
  2008.                                 ||      ( reg_exp )
  2009.  
  2010.                 trans_section ::=       translations
  2011.                                 ||      <nothing>
  2012.  
  2013.                 translations ::=        translations translation
  2014.                                 ||      translation
  2015.  
  2016.                 translation ::=         pattern action
  2017.                                 ||      %{ <anything> %}
  2018.                                 ||      %% <anything> <EOF>
  2019.  
  2020.                 pattern ::=             reg_exp / reg_exp
  2021.                                 ||      reg_exp
  2022.  
  2023.  
  2024.  
  2025.  
  2026.  
  2027.  
  2028.  
  2029.  
  2030.  
  2031.  
  2032.  
  2033.  
  2034.  
  2035.  
  2036.  
  2037.  
  2038.  
  2039.  
  2040.  
  2041.  
  2042.  
  2043.  
  2044.  
  2045.  
  2046.  
  2047.  
  2048.  
  2049.  
  2050.  
  2051.  
  2052.  
  2053.  
  2054.  
  2055.  
  2056.  
  2057.  
  2058.  
  2059.  
  2060.  
  2061.  
  2062.  
  2063.  
  2064.  
  2065.  
  2066.  
  2067.  
  2068.  
  2069.  
  2070.  
  2071.  
  2072.  
  2073.  
  2074.  
  2075.  
  2076.  
  2077.  
  2078.  
  2079.                                    APPENDIX B
  2080.  
  2081.                               SOME SMALL EXAMPLES
  2082.  
  2083.  
  2084.  
  2085.  
  2086.  
  2087.         The following example illustrates  the  use  of  the  look-ahead
  2088.         operator, and various other of the nuances of using LEX.
  2089.  
  2090.  
  2091.  
  2092.         B.1  A Complete Command
  2093.  
  2094.              _ ________ _______
  2095.  
  2096.  
  2097.         The C programming language has had two different ways of writing
  2098.         its  assignment  operators.   The original method was to write a
  2099.         binary operator immediately following  the  ordinary  assignment
  2100.         operator, forming a compound operator.  Thus 'a =+ b' caused the
  2101.         value of 'a+b' to be assigned to 'a'.  Similarly,
  2102.  
  2103.                 =- =/ =% =* =<< =>> =| =& =^
  2104.  
  2105.         were written  for  the  assignment  operators  corresponding  to
  2106.         subtraction,  division,  modulus,  multiplication,  left  shift,
  2107.         right shift, logical OR, logical AND, and exclusive OR.  In  the
  2108.         current  version of the language, the binary operator is written
  2109.         to the left of the  assignment  operator,  to  remove  potential
  2110.         ambiguity.
  2111.  
  2112.         The LEX program "ctoc"  is  a  filter  which  converts  programs
  2113.         written  in  the  older style into programs written in the newer
  2114.         style.   It  uses  the  look-ahead  operator,  and  the  various
  2115.         dis-ambiguating rules to ensure that sequences like
  2116.  
  2117.                 a==-1           a=++b
  2118.  
  2119.         remain unchanged.
  2120.  
  2121.  
  2122.  
  2123.  
  2124.  
  2125.  
  2126.  
  2127.  
  2128.  
  2129.  
  2130.  
  2131.  
  2132.  
  2133.  
  2134.         A Lexical Analyser Generator                               
  2135.         Some Small Examples
  2136.  
  2137.  
  2138.         /*
  2139.          * ctoc.lxi  --  Convert old C operators to new C form
  2140.          *
  2141.          * Adapted from example in C. Forsythe's LEX manual.
  2142.          *
  2143.          * NOTE:
  2144.          *      Forsythe's program put an entire comment into the token
  2145.          *      buffer. Either define a huge token buffer for my typical
  2146.          *      monster comments, or filter text within comments as if
  2147.          *      it were real C code. This is what I did. So =+ inside
  2148.          *      a comment will get changed to +=, etc.  Note tnat you
  2149.          *      may use the commen() function in LEXLIB if you want the
  2150.          *      comments eaten. I wanted 'em in the output.
  2151.          * by
  2152.          *      Bob Denny
  2153.          *      31-Feb-81
  2154.          */
  2155.         %{
  2156.         char tbuf[80];          /* Token buffer */
  2157.         main()
  2158.           {
  2159.           while (yylex())
  2160.             ;
  2161.           }
  2162.         %}
  2163.         any             = [\0-\177];
  2164.         nesc            = [^\\];
  2165.         nescquote       = [^\\"];
  2166.         nescapost       = [^\\'];
  2167.         schar           = "\\" any | nescquote;
  2168.         cchar           = "\\" any | nescapost;
  2169.         string          = '"' schar* '"';
  2170.         charcon         = "'" cchar* "'";
  2171.         %%
  2172.         "=" ( << | >> | "*" | + | - | "/" | "%" | "&" | "|" | "^" )
  2173.                         {
  2174.                         gettoken(tbuf, sizeof tbuf);
  2175.                         printf("%s=",tbuf+1);
  2176.                         }
  2177.         /*
  2178.          * The following will overflow the token buffer on any but a
  2179.          * small comment:
  2180.          */
  2181.         /*********
  2182.         "/*" ([^*] | "*"[^/])* "*/"
  2183.                 {
  2184.                         lexecho(stdout);
  2185.                 }
  2186.         **********/
  2187.         [<=>!]"=" | "="[<>]
  2188.                         {
  2189.                         lexecho(stdout);
  2190.                         }
  2191.         "=" / ( ++ | -- )
  2192.  
  2193.  
  2194.  
  2195.  
  2196.  
  2197.  
  2198.  
  2199.  
  2200.         A Lexical Analyser Generator                                    P
  2201.         Some Small Examples
  2202.  
  2203.  
  2204.                         {
  2205.                         lexecho(stdout);
  2206.                         }
  2207.         charcon
  2208.                         {
  2209.                         lexecho(stdout);
  2210.                         }
  2211.         string
  2212.                         {
  2213.                         lexecho(stdout);
  2214.                         }
  2215.         [\0-\377]
  2216.                         {
  2217.                         lexecho(stdout);
  2218.                         }
  2219.  
  2220.  
  2221.         Assuming the Decus compiler running on RSTS/E in RT11 mode,  the
  2222.         above program would be built and executed as follows:
  2223.  
  2224.                 mcr     lex -i ctoc.lxi -o ctoc.c
  2225.                 cc      ctoc/v
  2226.                 as      ctoc/d
  2227.                 link    ctoc=ctoc,c:lexlib,c:suport,c:clib/b:2000
  2228.  
  2229.                 mcr ctoc <old.c >new.c
  2230.  
  2231.  
  2232.  
  2233.  
  2234.         B.2  Interactive Lexical Analysis
  2235.  
  2236.              ___________ _______ ________
  2237.  
  2238.         The following program reads words from  the  terminal,  counting
  2239.         each  as they are entered.  The interaction with the operator is
  2240.         "natural" in the sense that processing for one line is  complete
  2241.         before  the  next  line is input.  To implement this program, it
  2242.         was necessary to include a special version  of  lexgetc()  which
  2243.         returns   <NULL>   if  the  current  line  has  been  completely
  2244.         transmitted to the parser.  Because the parser must  still  have
  2245.         some  look-ahead context, it will return the "end-of-line" token
  2246.         twice at  the  beginning  of  processing.   This  required  some
  2247.  
  2248.         _____
  2249.         additional tests in the main program.
  2250.  
  2251.         /*
  2252.          * Count words -- interactively
  2253.          */
  2254.         white   = [\n\t ];      /* End of a word        */
  2255.         eol     = [\0];         /* End of input line    */
  2256.         any     = [!-~];        /* All printing char's  */
  2257.         illegal = [\0-\377];    /* Skip over junk       */
  2258.         %{
  2259.         char            line[133];
  2260.         char            *linep          = &line;
  2261.         int             iseof           = 0;
  2262.  
  2263.  
  2264.  
  2265.  
  2266.  
  2267.  
  2268.         A Lexical Analyser Generator                                    Pag
  2269.         Some Small Examples
  2270.  
  2271.  
  2272.         int             wordct          = 0;
  2273.         #define T_EOL   1
  2274.         main()
  2275.         {
  2276.                 register int    i;
  2277.                 while ((i = yylex()) != 0) {
  2278.                         /*
  2279.                          * If the "end-of-line"  token  is
  2280.                          * returned  AND  we're  really at
  2281.                          * the end of  a  line,  read  the
  2282.                          * next line.  Note that T_EOL is
  2283.                          * returned twice when the program
  2284.                          * starts because of the nature of
  2285.                          * the look-ahead algorithms.
  2286.                          */
  2287.                         if (i == T_EOL && !is_eof
  2288.                                         && *linep == 0) {
  2289.                                 printf("* ");
  2290.                                 fflush(stdout);
  2291.                                 getline();
  2292.                         }
  2293.                 }
  2294.                 printf("%d words\n", wordct);
  2295.         }
  2296.         %}
  2297.         %%
  2298.         any(any)*       {
  2299.                                 /*
  2300.                                  * Write each  word  on  a
  2301.                                  * seperate output line.
  2302.                                  */
  2303.                                 lexecho(stdout);
  2304.                                 printf("\n");
  2305.                                 wordct++;
  2306.                                 return(LEXSKIP);
  2307.                         }
  2308.         eol             {
  2309.                                 return(T_EOL);
  2310.                         }
  2311.         white(white)*   {
  2312.                                 return(LEXSKIP);
  2313.                         }
  2314.         %%
  2315.         getline()
  2316.         /*
  2317.          * Read a line for lexgetc()
  2318.          */
  2319.         {
  2320.                 is_eof = (fgets(line, sizeof line, stdin)
  2321.                                 == NULL);
  2322.                 linep = &line;
  2323.         }
  2324.         lexgetc()
  2325.         /*
  2326.  
  2327.  
  2328.  
  2329.  
  2330.  
  2331.  
  2332.  
  2333.  
  2334.         A Lexical Analyser Generator                                    P
  2335.         Some Small Examples
  2336.  
  2337.  
  2338.          * Homemade  lexgetc  --  return zero while at the
  2339.          * end of an input line or EOF at end of file.  If
  2340.          * more on this line, return the next byte.
  2341.          */
  2342.         {
  2343.                 return(   (is_eof) ?            EOF
  2344.                         : (*linep == 0) ?       0
  2345.                         :                       *linep++);
  2346.         }
  2347.